package com.gexiaobao.pigeon.ui.fragment.mine.training

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.databinding.FragmentTrainingFlyMapBinding
import com.gexiaobao.pigeon.viewmodel.MyTrainingViewModel
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 18:17
 * @Describe    : 训放地图
 */
class FragmentTrainingFlyMap : BaseFragment<MyTrainingViewModel, FragmentTrainingFlyMapBinding>() {

    private var webViewHeaderValue = ""

    override fun initView(savedInstanceState: Bundle?) {
        webViewHeaderValue = KvUtils.decodeString(Constant.TOKEN)

        changeUIStatus()

        eventViewModel.toRefreshList.observeInFragment(this) {
            if (it) {
                mTrainingStatus = 2
                initData()
                changeUIStatus()
            }
        }
    }

    private fun changeUIStatus() {
        if (mTrainingStatus == 1) {
            mDatabind.tvNoTrainingContent.visibility = View.VISIBLE
            mDatabind.llWebView.visibility = View.GONE
        } else {
            mDatabind.tvNoTrainingContent.visibility = View.GONE
            mDatabind.llWebView.visibility = View.VISIBLE
        }
    }

    @SuppressLint("JavascriptInterface", "SetJavaScriptEnabled")
    override fun initData() {
        super.initData()
//        val webUrl = ApiService.SERVER_URL+"/u/v1/training/getMap/$mId"//测试
        val webUrl = Constant.TRAINING_MAP_URL + "/u/v1/training/getMap/$mId"//正式(上线啦，记得改配置)
        LogUtils.debugInfo(webUrl)
        val map = mapOf("x-token" to webViewHeaderValue)
        mDatabind.webView.loadUrl(webUrl, map)
        val webSettings = mDatabind.webView.settings
        webSettings.userAgentString = webSettings.userAgentString + "Android-Pigeon"
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE//不使用缓存，只从网络获取数据.
        //支持屏幕缩放
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        //扩大比例的缩放
        webSettings.useWideViewPort = true
        // 自适应屏幕
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.loadWithOverviewMode = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true//设置js可以直接打开窗口，如window.open()，默认为false
        webSettings.javaScriptEnabled = true//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        webSettings.setSupportZoom(true)//是否可以缩放，默认true
        webSettings.builtInZoomControls = false//是否显示缩放按钮，默认false
        webSettings.useWideViewPort = true//设置此属性，可任意比例缩放。大视图模式
        webSettings.loadWithOverviewMode = true//和setUseWideViewPort(true)一起解决网页自适应问题
        webSettings.domStorageEnabled = true//DOM Storage
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW//加载https和http混合模式

        mDatabind.webView.addJavascriptInterface(this, "android");//添加js监听 这样html就能调用客户端
        mDatabind.webView.webChromeClient = webChromeClient
        mDatabind.webView.webViewClient = webViewClient
    }

    private val webViewClient: WebViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView, url: String) {//页面加载完成
        }

        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            return super.shouldOverrideUrlLoading(view, url)
        }
    }

    private val webChromeClient: WebChromeClient = object : WebChromeClient() {

        override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            return super.onJsAlert(view, url, message, result)
        }

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
        }

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            if (mDatabind.progressBar != null) {
                mDatabind.progressBar.visibility = View.VISIBLE
                mDatabind.progressBar.progress = newProgress
                if (newProgress == 100) {
                    mDatabind.progressBar.visibility = View.GONE
                }
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvRefreshMap) {
            when (it) {
                mDatabind.tvRefreshMap -> {
                    mDatabind.webView.reload()
                }
            }
        }
    }

    override fun onDestroyView() {
        mDatabind.webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
        mDatabind.webView.clearHistory()
        mDatabind.webView.destroy()
        super.onDestroyView()
    }

    companion object {
        private var mId = 0
        private var mTrainingStatus: Int = -1//1 未开始，2 已开始，3 已结束
        fun newInstance(id: Int, trainingStatus: Int): FragmentTrainingFlyMap {
            mId = id
            mTrainingStatus = trainingStatus
            val fragment = FragmentTrainingFlyMap()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }
}